package utils
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.FileReference;
	import flash.net.URLRequest;
	import flash.net.URLVariables;
	
	import common.entities.FileInfo;

	public class DownloadFileUtil
	{
		/**
		 * 下载文件
		 * @param p_fileInfo 文件信息（至少要有name, size, resolvePath）;
		 * @param p_progressHandler 进度函数格式  function(uploadedBytes:Number, totalBytes:Number)
		 * @param p_callback 完成后回传数据函数无参数
		 * @return
		 */
		public static function download(p_fileInfo:FileInfo, p_progressHandler:Function, p_callback:Function = null):void
		{
//			ExternalInterface.call("window.open", ".download?fileName=" + p_fileInfo.name 
//				+ "&filePath=" + p_fileInfo.resolvePath, "_blank");
			var req:URLRequest = new URLRequest(".download");
			var uv:URLVariables = new URLVariables();
			uv.fileName = p_fileInfo.name;
			uv.filePath = p_fileInfo.resolvePath;
			req.data = uv;
			var file:FileReference = new FileReference();
			file.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			file.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
			file.addEventListener(ProgressEvent.PROGRESS, progressHandler);
			file.addEventListener(Event.COMPLETE, completeHandler);
			file.download(req, p_fileInfo.name);
			//下载进度显示函数
			function progressHandler(p_evt:ProgressEvent):void
			{
				if(p_progressHandler != null)
					p_progressHandler(p_evt.bytesLoaded, p_fileInfo.size);
			}
			//下载完成回调函数
			function completeHandler(p_evt:Event):void
			{
				removeEvents();
				if(p_callback != null)
					p_callback();
			}
			//安全沙箱错误
			function securityErrorHandler(p_evt:SecurityErrorEvent):void
			{
				removeEvents();
			}
			//文件读取出错
			function ioErrorHandler(p_evt:IOErrorEvent):void
			{
				removeEvents();
			}
			//移除事件
			function removeEvents():void
			{
				file.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
				file.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
				file.removeEventListener(ProgressEvent.PROGRESS, progressHandler);
				file.removeEventListener(Event.COMPLETE, completeHandler);
			}
		}
	}
}